package com.dimanche.module_course.app;

import android.app.Application;

import androidx.annotation.NonNull;
import androidx.lifecycle.ViewModel;
import androidx.lifecycle.ViewModelProvider;

import com.dimanche.library_db.repository.DirRepository;
import com.dimanche.module_course.data.CourseRepository;
import com.dimanche.module_course.data.source.Course100Source;
import com.dimanche.module_course.ui.main.MainViewModel;

/**
 * author : Dimanche
 * date   : 2021/3/26 22:58
 * desc   :
 * version: 1.0
 */
public class AppViewModelFactory extends ViewModelProvider.NewInstanceFactory {

    private static volatile AppViewModelFactory INSTANCE;
    private final Application mApplication;
    private final CourseRepository mCourseRepository;

    public static AppViewModelFactory getInstance(Application application) {
        if (INSTANCE == null) {
            synchronized (AppViewModelFactory.class) {
                if (INSTANCE == null) {
                    INSTANCE = new AppViewModelFactory(application, provideCourseRepository());
                }
            }
        }
        return INSTANCE;
    }

    public AppViewModelFactory(Application mApplication, CourseRepository mCourseRepository) {
        this.mApplication = mApplication;
        this.mCourseRepository = mCourseRepository;
    }


    private static CourseRepository provideCourseRepository() {
        Course100Source course100Source = new Course100Source();
        return CourseRepository.getInstance(course100Source, DirRepository.getInstance());

    }

    @NonNull
    @Override
    public <T extends ViewModel> T create(@NonNull Class<T> modelClass) {
        if (modelClass.isAssignableFrom(MainViewModel.class)) {
            return (T) new MainViewModel(mApplication, mCourseRepository);
        }
        throw new IllegalArgumentException("Unknown ViewModel class: " + modelClass.getName());
    }
}
